package com.foreveredu.propms.web.struts.action;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.foreveredu.propms.domain.Account;
import com.foreveredu.propms.domain.ChargeCriterion;
import com.foreveredu.propms.domain.ChargeItem;
import com.foreveredu.propms.domain.Exchange;
import com.foreveredu.propms.domain.House;
import com.foreveredu.propms.domain.Owner;
import com.foreveredu.propms.domain.SubAccount;
import com.foreveredu.propms.domain.User;
import com.foreveredu.propms.service.IBusinessService;
import com.foreveredu.propms.service.IChargeService;
import com.foreveredu.propms.service.IManagementService;
import com.foreveredu.propms.web.struts.actionform.AccountActionForm;
import com.foreveredu.propms.web.util.DigitalUpperCase;

/**
 * 处理业主账户请求
 * @author hushigang
 *
 */
public class AccountAction extends AbstractBaseDispatchAction {

	private IBusinessService businessService = null;
	private IManagementService managementService = null;
	private IChargeService chargeService = null;
	
	//获得日志记录器
	//Logger log = Logger.getLogger(AccountAction.class);
	
	public IManagementService getManagementService() {
		return managementService;
	}

	public void setManagementService(IManagementService managementService) {
		this.managementService = managementService;
	}

	public IBusinessService getBusinessService() {
		return businessService;
	}

	public void setBusinessService(IBusinessService businessService) {
		this.businessService = businessService;
	}

	public IChargeService getChargeService() {
		return chargeService;
	}

	public void setChargeService(IChargeService chargeService) {
		this.chargeService = chargeService;
	}

	// 跳转业主信息搜索条件页面
	public ActionForward toSearch(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			
		return mapping.findForward("toSearch");
	}
	
	// 跳转到预存费用页面
	public ActionForward toDeposit(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		AccountActionForm aaf = (AccountActionForm)form;
		
		String houseId = aaf.getHouseId();
		String ownerName = aaf.getOwnerName();
		String phone = aaf.getPhone();
		String idCard = aaf.getIdCard();
		
		//获得业主信息
		Owner owner = null;
		if (houseId != null && !houseId.trim().equals("")) {
			House house = managementService.findHouseByHouseId(houseId);
			if (house != null) {
				owner = house.getOwner();
			}
		} else if (ownerName != null && !ownerName.trim().equals("")) {
			owner = managementService.findOwnerByName(ownerName);
		} else if (phone != null && !phone.trim().equals("")) {
			owner = managementService.findOwnerByPhone(phone);
		} else if (idCard != null && !idCard.trim().equals("")) {
			owner = managementService.findOwnerByIdCard(idCard);
		}
		
		//判断是否save方法验证不通过，从而跳转过来
		if (request.getAttribute("owner") != null) {
			owner = (Owner)request.getAttribute("owner");
		}
		
		//表单验证
		if(owner == null) {
			request.setAttribute("ownerNotFoundError", "没有找到该业主信息");
			return mapping.findForward("toSearch");
		}
		
		//显示业主账户当前余额
		float balance = 0;
		Account account = businessService.findAccountByOwner(owner);
		if(account != null) {
			balance = account.getBalance();
		}
		request.setAttribute("balance", balance);
		request.setAttribute("owner", owner);
		
		Set<House> houseSet = owner.getHouses();
		request.setAttribute("houseSet", houseSet);
		
		
		double money1 = 0;//预收物业服务费（半年）
		double money2 = 0;//预收装修保证金
		double money3 = 0;//预收装修服务费
		double money4 = 0;//预收装修垃圾清运费
		if (houseSet != null) {
			double money = 0;
			for(House house : houseSet) {
				//获得该房产的所有收费项目
				Set<ChargeItem> items = house.getChargeItems();
				for(ChargeItem item : items) {
					//查找该房产应缴纳的收费项目所对应的物业收费标准
					ChargeCriterion cc = null; 
					
					//单独物业服务收费项目
					if (item.getItemId().equals("2")) {
						cc = chargeService.findCriterionByHouseAndItem(house,item,house.getBuilding().getSubDistrict());
					} else {
						cc = chargeService.findCriterionByTypeAndItem(house.getType(), house.getBuilding().getType(), house.getSource(), item, house.getBuilding().getSubDistrict());
					}
					
					switch (Integer.parseInt(item.getItemId())) {
					case 1:
						//物业管理费
						money = Double.parseDouble(new DecimalFormat("0.00").format(house.getArea()*cc.getAmount()));
						money1 += money;
						break;

					case 2:
						//单独物业服务费
						money = Double.parseDouble(new DecimalFormat("0.00").format(cc.getAmount()));
						money1 += money;
						break;

					case 10:
						//装修保证金
						money = Double.parseDouble(new DecimalFormat("0.00").format(cc.getAmount()));
						money2 += money;
						break;

					case 11:
						//装修服务费
						money = Double.parseDouble(new DecimalFormat("0.00").format(cc.getAmount()));
						money3 += money;
						break;
						
					case 9:
						//装修垃圾清运费
						money = Double.parseDouble(new DecimalFormat("0.00").format(cc.getAmount()));
						money4 += money;
						break;						
					}
				}
			}
		}
		
		request.setAttribute("money1", money1);
		request.setAttribute("money2", money2);
		request.setAttribute("money3", money3);
		request.setAttribute("money4", money4);
		
		return mapping.findForward("toDeposit");
	}

	// 保存业主预存费用
	public ActionForward save(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		AccountActionForm aaf = (AccountActionForm)form;
		
		Owner owner = managementService.findOwnerById(aaf.getOwnerId());
		request.setAttribute("owner", owner);
		
		/*
		 * amounts数组，
		 * 第1项代表物业服务费，
		 * 第2项代表装修保证金，
		 * 第3项代表装修服务费，
		 * 第4项代表装修垃圾清运费
		 * 第5项代表预存金额
		 */
		float[] amounts = aaf.getAmount();
		float allAmount = 0;
		for(float amount: amounts) {
			if(amount < 0) {
				request.setAttribute("depositLeastZeroError", "存入金额必须大于零！");
				request.setAttribute("owner", owner);
				return mapping.findForward("toDepositAction");
			}
			allAmount += amount;
		}
		if (allAmount == 0) {
			request.setAttribute("depositAllZeroError", "至少有一项存入金额必须大于零！");
			return mapping.findForward("toDepositAction");
		}
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		
		//查找该业主是否已经开通账户，如果没有则开通账户，否则将存入金额累加到账户余额中
		Account account = businessService.findAccountByOwner(owner);
		if (account == null) {
			//创建新账户
			account = new Account();
			account.setOwner(owner);
			account.setBalance(allAmount);
			account.setLastUsedDate(date);
			businessService.saveAccount(account);
			
			//创建各个子账户
			for(int i = 0; i < amounts.length; i++) {
				if (amounts[i] != 0) {
					SubAccount subAccount = new SubAccount();
					subAccount.setAccount(account);
					subAccount.setType(i+1);
					subAccount.setBalance(amounts[i]);
					businessService.saveSubAccount(subAccount);				
				}
			}
		} else {
			//修改子账户金额
			Set<SubAccount> subAccounts = account.getSubAccounts();
			for(SubAccount subAccount : subAccounts) {
				if (subAccount.getType() == 2 && amounts[1] > 0) {
					request.setAttribute("type2ExistsError", "装修保证金只需缴纳一次！");
					return mapping.findForward("toDepositAction");
				}
				if (subAccount.getType() == 3 && amounts[2] > 0) {
					request.setAttribute("type3ExistsError", "装修服务费只需缴纳一次！");
					return mapping.findForward("toDepositAction");
				}
				if (subAccount.getType() == 4 && amounts[3] > 0) {
					request.setAttribute("type3ExistsError", "装修垃圾清运费只需缴纳一次！");
					return mapping.findForward("toDepositAction");
				}	
				if (subAccount.getType() == 1 && amounts[0] > 0) {
					subAccount.setBalance(subAccount.getBalance()+amounts[0]);
					businessService.updateSubAccount(subAccount);
				}
				if (subAccount.getType() == 5 && amounts[4] > 0) {
					subAccount.setBalance(subAccount.getBalance()+amounts[4]);
					businessService.updateSubAccount(subAccount);
				}
			}
			account.setBalance(account.getBalance()+allAmount);
			account.setLastUsedDate(date);
			businessService.updateAccount(account);
			
		}
		
		//保存账户交易记录
		Exchange exchange = new Exchange();
		exchange.setAccount(account);
		exchange.setBalance(account.getBalance());
		exchange.setDeposit(allAmount);
		exchange.setExtime(date);
		businessService.saveExchange(exchange);
		
		//统计业主的全部房产的历史欠款
		float historyDebt = businessService.findHistoryDebtOfOwner(owner);
		request.setAttribute("historyDebt", Float.parseFloat(new DecimalFormat("0.00").format(historyDebt)));

		// 收费员	/抄表员 /开票员：当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		request.setAttribute("nickname", user.getNickname());
 
		//开票日期：
		request.setAttribute("invoiceDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		
		request.setAttribute("balance", account.getBalance());
		request.setAttribute("allAmount", allAmount);
		request.setAttribute("allAmountUpperCase", DigitalUpperCase.toUpperCase(allAmount));
		
		request.setAttribute("year", Calendar.getInstance().get(Calendar.YEAR));
		request.setAttribute("month", Calendar.getInstance().get(Calendar.MONTH) + 1);
		
		request.setAttribute("amounts", amounts);
		
		//显示业主的房产及小区信息，如果业主有多个房产，则取第1个房产
		House house = (House)owner.getHouses().toArray()[0];
		request.setAttribute("house", house);
		
		//计算业主缴纳物业服务费的期限
		double critria = aaf.getCriteria();
		if (amounts[0] != 0) {
			int period = (int)(amounts[0] / critria);
			Calendar c =  Calendar.getInstance();
			c.add(Calendar.MONTH, period);
			String endDate = c.get(Calendar.YEAR)+"年"+(c.get(Calendar.MONTH)+1)+"月";
			request.setAttribute("endDate", endDate);
		}
		
		return mapping.findForward("saveDone");
	}

	// 跳转退还装修保证金的业主信息搜索条件页面
	public ActionForward toRefundSearch(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
			
		return mapping.findForward("toRefundSearch");
	}
	
	// 跳转到退还装修保证金的操作页面
	public ActionForward toRefund(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		AccountActionForm aaf = (AccountActionForm)form;
		
		String houseId = aaf.getHouseId();
		String ownerName = aaf.getOwnerName();
		String phone = aaf.getPhone();
		String idCard = aaf.getIdCard();
		
		//获得业主信息
		Owner owner = null;
		if (houseId != null && !houseId.trim().equals("")) {
			House house = managementService.findHouseByHouseId(houseId);
			if (house != null) {
				owner = house.getOwner();
			}
		} else if (ownerName != null && !ownerName.trim().equals("")) {
			owner = managementService.findOwnerByName(ownerName);
		} else if (phone != null && !phone.trim().equals("")) {
			owner = managementService.findOwnerByPhone(phone);
		} else if (idCard != null && !idCard.trim().equals("")) {
			owner = managementService.findOwnerByIdCard(idCard);
		}
		
		//表单验证
		if(owner == null) {
			request.setAttribute("ownerNotFoundError", "没有找到该业主信息");
			return mapping.findForward("toRefundSearch");
		}
		
		//查询当前业主是否已经缴纳装修保证金
		float refund = 0;
		Account account = businessService.findAccountByOwner(owner);
		if(account != null) {
			SubAccount subAccount = businessService.findSubAccountByType(account, 2);
			if (subAccount != null && subAccount.getBalance() > 0) {
				refund = subAccount.getBalance();
			}
		}
		
		request.setAttribute("owner", owner);
		
		Set<House> houseSet = owner.getHouses();
		request.setAttribute("houseSet", houseSet);
		
		//将装修保证金发送到页面
		request.setAttribute("refund", refund);
		
		return mapping.findForward("toRefund");
	}
	
	// 执行退还业主装修保证金操作
	public ActionForward refund(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//获得表单数据
		AccountActionForm aaf = (AccountActionForm)form;
		
		Owner owner = managementService.findOwnerById(aaf.getOwnerId());
		request.setAttribute("owner", owner);
		
		String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		
		//从该业主装修保证金子账户中退还押金
		Account account = businessService.findAccountByOwner(owner);
		SubAccount subAccount = businessService.findSubAccountByType(account, 2);
		float refund = subAccount.getBalance();//业主缴纳的装修保证金的具体金额

		account.setBalance(Float.parseFloat(new DecimalFormat("#.00").format(account.getBalance()-refund)));
		account.setLastUsedDate(date);
		businessService.updateAccount(account);
		
		subAccount.setBalance(0);
		businessService.updateSubAccount(subAccount);			
		
		//保存账户交易记录
		Exchange exchange = new Exchange();
		exchange.setAccount(account);
		exchange.setBalance(account.getBalance());
		exchange.setWithdraw(refund);
		exchange.setExtime(date);
		businessService.saveExchange(exchange);
		
		//统计业主的全部房产的历史欠款
		float historyDebt = businessService.findHistoryDebtOfOwner(owner);
		request.setAttribute("historyDebt", Float.parseFloat(new DecimalFormat("0.00").format(historyDebt)));

		// 收费员	/抄表员 /开票员：当前登录用户
		User user = null;
		try {
			user = managementService.findUserByUsername(this.getPrincipal().getUsername());
		} catch(ClassCastException e) {
			//用户长时间不操作，session丢失后，跳转到登录页面
			return mapping.findForward("login");
		}
		request.setAttribute("nickname", user.getNickname());
 
		//开票日期：
		request.setAttribute("invoiceDate", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
		
		request.setAttribute("balance", account.getBalance());
		request.setAttribute("refund", refund);
		request.setAttribute("refundUpperCase", DigitalUpperCase.toUpperCase(refund));
		
		request.setAttribute("year", Calendar.getInstance().get(Calendar.YEAR));
		request.setAttribute("month", Calendar.getInstance().get(Calendar.MONTH) + 1);
		
		//显示业主的房产及小区信息，如果业主有多个房产，则取第1个房产
		House house = (House)owner.getHouses().toArray()[0];
		request.setAttribute("house", house);
		
		return mapping.findForward("refundDone");
	}
} 
